package com.bsoft.gol.hcs.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

	/**
	 * @param str
	 * @throws
	 * @description: 校验一个字符串是否可转化为long
	 * @return: boolean
	 * @author: tongtp
	 * @date: 2020/3/12 14:55
	 */
	public static boolean isValidLong(String str) {
		try {
			long _v = Long.parseLong(str);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}



	/**
	 * 将url参数转换成map
	 * @param param aa=11&bb=22&cc=33
	 * @return
	 */
	public static Map<String, Object> getUrlParams(String param) {
		Map<String, Object> map = new HashMap<String, Object>(0);
		if (StringUtils.isBlank(param)) {
			return map;
		}
		String[] params = param.split("&");
		for (int i = 0; i < params.length; i++) {
			String[] p = params[i].split("=");
			if (p.length == 2) {
				map.put(p[0], p[1]);
			}
		}
		return map;
	}

	/**
	 * @param obj
	 * @return Integer return zero if any Exception throw
	 */
	public static Integer toInteger(Object obj) {
		return toInteger(obj, true);
	}

	/**
	 * @param obj
	 * @param : return zero if any Exception throw
	 * @return Integer
	 */
	public static Integer toInteger(Object obj, Boolean zero) {
		return toInteger(toString(obj, zero), zero);
	}

	/**
	 * @param str
	 * @return Integer return zero if any Exception throw
	 */
	public static Integer toInteger(String str) {
		return toInteger(str, true);
	}

	/**
	 * @param str
	 * @param true: return zero if any Exception throw
	 * @return Integer
	 */
	public static Integer toInteger(String str, Boolean zero) {
		Integer retInt = 0;

		try {
			retInt = Integer.parseInt(str);
		} catch (Exception ex) {
			if (!zero) {
                retInt = null;
            }
		}

		return retInt;
	}

	/**
	 * @param obj
	 * @return Short return zero if any Exception throw
	 */
	public static Short toShort(Object obj) {
		return toShort(obj, true);
	}

	/**
	 * @param obj
	 * @param true: return zero if any Exception throw
	 * @return Short
	 */
	public static Short toShort(Object obj, Boolean zero) {
		return toShort(toString(obj, zero), zero);
	}

	/**
	 * @param str
	 * @return Short return zero if any Exception throw
	 */
	public static Short toShort(String str) {
		return toShort(str, true);
	}

	/**
	 * @param str
	 * @param true: return zero if any Exception throw
	 * @return Short
	 */
	public static Short toShort(String str, Boolean zero) {
		Short retShort = 0;

		try {
			retShort = Short.parseShort(str);
		} catch (Exception ex) {
			if (!zero) {
                retShort = null;
            }
		}

		return retShort;
	}

	/**
	 * @param obj
	 * @return Long return zero if any Exception throw
	 */
	public static Long toLong(Object obj) {
		return toLong(toString(obj));
	}

	/**
	 * @param obj
	 * @param true: return zero if any Exception throw
	 * @return Long
	 */
	public static Long toLong(Object obj, Boolean zero) {
		return toLong(toString(obj, zero), zero);
	}

	/**
	 * @param str
	 * @return Long return zero if any Exception throw
	 */
	public static Long toLong(String str) {
		return toLong(str, true);
	}

	/**
	 * @param str
	 * @param true: return zero if any Exception throw
	 * @return Long
	 */
	public static Long toLong(String str, Boolean zero) {
		Long retLong = 0L;

		try {
			retLong = Long.parseLong(str);
		} catch (Exception ex) {
			if (!zero) {
                retLong = null;
            }
		}

		return retLong;
	}

	/**
	 * @param obj
	 * @return String return empty if any Exception throw
	 */
	public static String toString(Object obj) {
		return toString(obj, true);
	}

	/**
	 * @param obj
	 * @param true: return empty if any Exception throw
	 * @return String
	 */
	public static String toString(Object obj, Boolean zero) {
		String retStr = "";

		try {
			retStr = obj.toString();
		} catch (Exception ex) {
			if (!zero) {
                retStr = null;
            }
		}

		return retStr;
	}

	/**
	 * @param str
	 * @param int the length after truncated
	 * @return string after truncated
	 */
	public static String truncate(String str, Integer len) {
		if (str.length() > len) {
			return str.substring(0, len) + "...";
		} else {
			return str;
		}
	}

	/**
	 * 保存文件
	 *
	 * @param stream
	 * @param path
	 * @param filename
	 * @throws IOException
	 */
	public static void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
		FileOutputStream fs = new FileOutputStream(path + "/" + filename);
		byte[] buffer = new byte[1024 * 1024];
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}

	/*
	 * Java文件操作 获取文件扩展名
	 */
	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	//	public static void reflect(IdEntity e) throws Exception {
	//		Class cls = e.getClass();
	//		Field[] fields = cls.getDeclaredFields();
	//		for (int i = 0; i < fields.length; i++) {
	//			Field f = fields[i];
	//			f.setAccessible(true);
	//			System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(e));
	//		}
	//	}
	//
	//	public static List getreflect(IdEntity e) throws Exception {
	//		List al = new ArrayList();
	//		Class cls = e.getClass();
	//		Field[] fields = cls.getDeclaredFields();
	//		for (int i = 0; i < fields.length; i++) {
	//			Field f = fields[i];
	//			f.setAccessible(true);
	////			System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(e));
	//			al.add(f.get(e));
	//		}
	//		return al;
	//	}

	/**
	 * 获取固定长度的随机数
	 * @param strLength 随机数长度
	 * @return 随机数
	 */
	//    public static String getFixLenthString(int strLength) {
	//        Random rm = new Random();
	//
	//        // 获得随机数
	//        double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
	//
	//        // 将获得的获得随机数转化为字符串
	//        String fixLenthString = String.valueOf(pross);
	//
	//        // 返回固定的长度的随机数
	//        return fixLenthString.substring(1, strLength + 1);
	//    }

	/**
	 * 获取百分比的方法
	 * @param fz
	 * @param fm
	 * @return
	 */
	public static String getBFB(double fz,double fm){
		int scale = 2;
		DecimalFormat df = (DecimalFormat)NumberFormat.getInstance();
		//可以设置精确几位小数
		df.setMaximumFractionDigits(scale);
		 //模式 例如四舍五入
		df.setRoundingMode(RoundingMode.HALF_UP);
		double accuracy_num = fz/fm*100;
		String bfbz = "";
		if(Double.isNaN(accuracy_num)){
			bfbz = "0%";
		}else{
			bfbz = df.format(accuracy_num)+"%";
		}
		return bfbz;
	}

	/**
	 * 获取百分比的方法
	 * @param fz
	 * @param fm
	 * @return
	 */
	public static Double getBFBDouble(double fz,double fm){
		int scale = 2;
		DecimalFormat df = (DecimalFormat)NumberFormat.getInstance();
		//可以设置精确几位小数
		df.setMaximumFractionDigits(scale);
		 //模式 例如四舍五入
		df.setRoundingMode(RoundingMode.HALF_UP);
		double accuracy_num = fz/fm*100;
		String bfbz = "";
		if(Double.isNaN(accuracy_num)){
			bfbz = "0";
		}else{
			bfbz = df.format(accuracy_num)+"";
		}
	    Double fhz = Double.valueOf(bfbz);
		return fhz;
	}


	/**
	 * 获取uuid
	 * @return
	 */
	public static String getUUID(){
		String uuid = UUID.randomUUID().toString();
		//去掉“-”符号 Html2Text
		return uuid.replaceAll("-", "");
	}


	 public static String getYearLast(int year){
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	        Calendar calendar = Calendar.getInstance();
	        calendar.clear();
	        calendar.set(Calendar.YEAR, year);
	        calendar.roll(Calendar.DAY_OF_YEAR, -1);
	        Date currYearLast = calendar.getTime();
	        return sdf.format(currYearLast);
	 }


	 public static String getMonthLast(String time){
	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    	int year = Integer.parseInt(time.substring(0,4));
	    	int month = Integer.parseInt(time.substring(5,7));
	    	Calendar cal = Calendar.getInstance();
	        //设置年份
	        cal.set(Calendar.YEAR,year);
	        //设置月份
	        cal.set(Calendar.MONTH, month-1);
	        //获取某月最大天数
	        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
	        //设置日历中月份的最大天数
	        cal.set(Calendar.DAY_OF_MONTH, lastDay);
	        //格式化日期
	        String lastDayOfMonth = sdf.format(cal.getTime());
	        return lastDayOfMonth;
	 }

	 /**
	  * 获取提前的时间
	  * @param minute 分钟数
	  * @return
	  */
	 public static String getAdvanceTime(int minute){
		 Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	     Date today1 = new Date();
	     Calendar c1 = Calendar.getInstance();
	     c1.setTime(today1);
	     c1.add(Calendar.MINUTE, minute);
		 return f.format(c1.getTime())+":00";
	 }

	public static String Html2Text(String inputString){
		String htmlStr = inputString; //含html标签的字符串
		String textStr ="";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		try{
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
			String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
			p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); //过滤script标签
			p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); //过滤style标签
			p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); //过滤html标签
			textStr = htmlStr;
		}catch(Exception e){
			e.printStackTrace();
		}
		return textStr;//返回文本字符串
	}
	/**
	 * 自己写的string.trim()方法，去除首尾指定的字符串
	 * @param str 要去除首尾的字符串
	 * @param string 需要删掉的字符串
	 * @return 去掉首尾字符的字符串
	 */
	public static String trim(String str, String string) {
		int len, strlen = string.length();
		while (true) {
			len = str.length();
			boolean strBegin = str.substring(0, strlen).equals(string);
			boolean strEnd = str.substring(len - strlen).equals(string);
			str = strBegin ? str.substring(strlen) : str;
			len = str.length();
			str = strEnd ? str.substring(0, len - strlen) : str;
			if (!strBegin && !strEnd) {
				break;
			}
		}
		return str;
	}

	public static boolean isPhone(String phone) {
		String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,2,3,5,6,7,8])|(18[0-9])|(19[1,3,5,8,9]))\\d{8}$";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(phone);
		return m.matches();

	}
}
